package com.ld.spring.source.handler;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @author littlelot
 */
public class MessageHandler {

    private static String handshakeHex = "68616e647368616b65c7c7cbcd759aeb6861302dc72c0a2020273339273a2031";
    private static String sendshakeHex = "68616e647368616b656775d432232f5034c1";

    public static void handle(Socket socket) {
        try (InputStream is = socket.getInputStream(); OutputStream os = socket.getOutputStream()) {
            byte[] bytes = new byte[2048];
            int len = 0;
            while ((len = is.read(bytes)) != 0) {
                if (len != -1) {
                    System.out.println("server: " + new String(bytes, 0, len) + " : " + bytesToHex(bytes, 0, len));
                    // if (bytesToHex(bytes, 0, len).equals(handshakeHex)) {
                    byte[] buf = hexToByteArray(sendshakeHex);
                    System.out.println("client: " + new String(buf, 0, buf.length) + " : " + sendshakeHex);
                    os.write(buf);
                    os.flush();
                    // } else {
                    // System.out.println("无法匹配");
                    // }

                    // try {
                    // Thread.sleep(1000);
                    // } catch (InterruptedException e) {
                    // e.printStackTrace();
                    // }
                } else {
                    System.out.println("已达到文件结尾");
                    byte[] buf = hexToByteArray(sendshakeHex);
                    System.out.println("client: " + new String(buf, 0, buf.length) + " : " + sendshakeHex);
                    os.write(buf);
                    os.flush();
                }
            }
            throw new Exception("服务端已关闭连接,握手失败");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String bytesToHex(byte[] bytes, int start, int len) {
        StringBuffer sb = new StringBuffer();
        for(int i = start; i < start + len; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() < 2) {
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    public static byte[] hexToByteArray(String inHex) {
        int hexlen = inHex.length();
        byte[] result;
        if (hexlen % 2 == 1){
            hexlen++;
            result = new byte[(hexlen / 2)];
            inHex = "0" + inHex;
        }else {
            result = new byte[(hexlen / 2)];
        }
        int j = 0;
        for (int i = 0; i < hexlen; i += 2){
            result[j] = hexToByte(inHex.substring(i, i + 2));
            j++;
        }
        return result;
    }

    private static byte hexToByte(String hex) {
        return (byte) Integer.parseInt(hex, 16);
    }
}
